<?php

namespace App\Http\Controllers\Home;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

class OrderController extends Controller
{
    public function isUserExist(Request $request){
        DB::connection()->enableQueryLog();
        $usertel = intval($request->get('usertel'));
        $userid = intval($request->get('userid'));
        $username = trim($request->get('username'));
        if($usertel == 0 && $userid == 0 && $username == ''){
            return 0; //参数全部为空
        }else{
            $info = DB::table('waihui_member')
                    ->where('tel',"$usertel")
                    ->orWhere('id',$userid)
                    ->orWhere('username',"$username")
                    ->first();
//            $queries = DB::getQueryLog(); 
//            dd($queries);
            if($info){ //查询用户漏单情况
                return $info->id;
            }else{
                return 1; //此用户不存在
            }
        }
    }
    
    //查询用户订阅和漏单的详细情况
    public function loudan(Request $request){
        $id = intval($request->get('userid'));
        if($id == 0){
            $return['code'] = 0;
            $return['msg'] = '请求参数错误';
            return json_encode($return);
        }
        $userinfodata = DB::table('waihui_member')->select('tel','username','id')->where('id',$id)->first();
        $return['userinfo'] = $userinfodata;
        $tel = $userinfodata->tel;
        $follow = DB::table('waihui_follow as f')
                ->join('waihui_member as m','f.analyst_id','m.id')
                ->select('m.tel','m.username','f.follow_time','f.update_time','f.direction')
                ->where([['follower_id','=',$id],['status','=',1]])
                ->get();
        
        if(!$follow || count($follow) == 0){
            $return['code'] = 1;
            $return['msg'] = '该用户没有订阅分析师';
            return json_encode($return);
        }
        
        foreach($follow as $k=>$v){
            $followTime = $v->update_time != '' ? $v->update_time :$v->follow_time;
            //echo "该用户订阅了: $v->username ，订阅时间: ".date('Y-m-d H:i:s',$followTime)."，方向：$v->direction, 手机号：$v->tel<br/>";
            $follow[$k]->handan =   DB::table('waihui_order')
                                    ->select('tradeid','isstop')
                                    ->where([['tel','=',$v->tel],['begin_time','>',$followTime]])
                                    ->orderBy('begin_time','desc')
                                    ->get();
            $follow[$k]->gendan  =  DB::table('waihui_gendan')
                                    ->select('tradeid')
                                    ->where([['follower_tel','=',$tel],['analyst_tel','=',$v->tel],['begin_time','>',$followTime]])
                                    ->orderBy('begin_time','desc')
                                    ->get();
            $follow[$k]->allhandancount = count($follow[$k]->handan);
            $follow[$k]->allgendancount = count($follow[$k]->gendan);
            //echo $v->username."喊单记录,共<font color=red>".$allhandancount."</font>单：<br/>";
            $handan = array();
            if($follow[$k]->handan){
                foreach($follow[$k]->handan as $kk=>$kv){
                    $handan[] = trim($kv->tradeid);
                }
            }
            //$follow[$k]->handanorder = $handan;
            
            //echo "该客户跟随".$v->username."跟单记录：共<font color=red>".$allgendancount."</font>单：<br/>";
            $gendan = array();
            if($follow[$k]->gendan){
                foreach($follow[$k]->gendan as $f){
                    $gendan[] = trim($f->tradeid);
                }
            }   
           // $follow[$k]->gendanorder = $gendan;
            $loudan = [];
            foreach($handan as $yy=>$vv){
                if(!in_array($vv, $gendan)){
                    $loudan[$yy]['orderData']= DB::table('waihui_order')
                                               ->select(DB::raw('FROM_UNIXTIME(begin_time,"%Y-%m-%d %H:%i:%s") as begin_time'),'typename','tradeid')
                                               ->where('tradeid',$vv)
                                               ->first();
                    //echo $vv.'(<font color=red>入场时间'.date('Y-m-d H:i:s',$orderData->begin_time).',品种：'.$orderData->typename.'</font>),漏单原因：';
                    $reason = DB::table('waihui_gendan_fail')->where([['tradeid','=',$vv],['follower_tel','=',$tel]])->value('reason');
                    if(!$reason){
                        $reason = '跟单失败表里没有记录这条信息'; 
                    }
                    $loudan[$yy]['orderData']->reason = $reason;
                }
                $follow[$k]->loudan = $loudan;
            }
            
        } 
        //dd($follow);
        foreach($follow as $k=>$val){
            $follow[$k]->follow_time = date('Y-m-d H:i:s',$val->follow_time);
            if($follow[$k]->update_time != ''){
                $follow[$k]->update_time = date('Y-m-d H:i:s',$val->update_time);
            }
        }
        $return['code'] = 2;
        $return['msg'] = '请求成功';
        $return['loudan'] = $follow;
        
       return json_encode($return);
    }
    
    //查询以某个字符开头的用户名
    public function nameStart(Request $request){
        $start = trim($request->get('namestart'));
        if($start == ''){ 
            return 0;
        }
        $usernameData = DB::table('waihui_member')->select('username')->where('username','like',"$start%")->get();
        if($usernameData != ''){
            return $usernameData;
        }
    }
    
    //小程序请求登录接口
    public function login(Request $request){
        //$data  = $GLOBALS['HTTP_RAW_POST_DATA'];
        
        $tel = trim($request->get('tel'));
        $password = trim($request->get('password'));
        //如果小程序是post请求此接口，那么请求必须加上此header，才可以用$_POST方式获取数据
        //如果不加此header，只能用laravel的$request->get()方式或者php的$GLOBALS['HTTP_RAW_POST_DATA']获取
//        header:{
//            'content-type': 'application/x-www-form-urlencoded'   //PHP默认识别的数据类型
//        },
      
        if($tel == '' || $password == ''){
            return json_encode(array('status'=>0)); //手机号和密码都不能为空
        }
        $isExist = DB::table('waihui_member')->select('id','username','photo')->where([['tel','=',"$tel"],['password','=',md5($password)]])->first();
        if($isExist->id){
            $token = getWxToken();
            return json_encode(array('status'=>1,'userinfo'=>array('userid'=> $isExist->id,'username'=> $isExist->username,'tel'=>$tel),'token'=>$token,));
        }else{
            return json_encode(array('status'=>0)); //账号或者密码错误  
        }
    }
    
    //设置VIP
    public function setvip(Request $request){
        $tel = trim($request->get('tel'));
        $username = trim($request->get('username'));
        $expireTime = trim($request->get('expiretime'));
        //$currentTime = now();
        if(!preg_match("/^1[34578]\d{9}$/",$tel) || $username == '' || $expireTime == ''){
            return array('code'=>0,'msg'=>'参数错误'); 
        }else if(strtotime($expireTime) < time()){
            return array('code'=>0,'msg'=>'日期错误'); 
        }else{
            $expireTime = strtotime($expireTime);
        }
        
        $data = DB::table('waihui_member')->where([['tel','=',"$tel"],['username','=',"$username"]])->first();
        if(!$data){
            return array('code'=>0,'msg'=>'信息不存在'); 
        }else{
            if($data->isvip != 0 && $data->expire_time > time() ){ //如果此用户vip还未过期
                return array('code'=>1,'expiretime'=>date('Y-m-d',$data->expire_time),'msg'=>'此用户vip还没过期');
            }else{
                $res = DB::table('waihui_member')->where([['tel','=',"$tel"],['username','=',"$username"]])->update(['isvip'=>'3','expire_time'=>$expireTime]);
                if($res){
                    return array('code'=>2,'msg'=>'设置成功'); 
                }else{
                    return array('code'=>3,'msg'=>'设置失败'); 
                }
            }
        }
    }
    
    //活动页面每周前十名入库
    public function winAward(){
        if(date('w') != 0){
            return array('code'=>0,'msg'=>'今天不是周日，不能入库');
        }
        $weekTime = DB::table('waihui_active_ranking')->select('week_time')->orderby('id','desc')->value('week_time');
        if(date('Y-m-d',$weekTime) == date('Y-m-d')){
            return array('code'=>1,'msg'=>'这周的排行已经入过库了');
        }
        
        $where['o.isstop']     = 0; //已平仓
        $where['o.ispersonal'] = 0; //网站下单的
        
        $weekstarttime  = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上6:00:00
        $weekendtime    = strtotime(date("Y-m-d H:i:s",mktime(12,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00
        $dataarr    = DB::table('waihui_member as m')
                    ->leftJoin('waihui_order as o', 'm.tel', 'o.tel')
                    ->select('m.id', 'm.tel', 'm.username', 'm.photo', DB::raw('SUM(final_point) as week_final_point'), DB::raw('count(o.tel) as ordernum'), DB::raw("(SUM(final_point)/count(o.tel)) AS single_final_point"), DB::raw("(count(case when o.trade_status='1' then 1 end) / count(o.tel))*100 AS winrate"))
                    ->where($where)
                    ->whereBetween('o.end_time', [$weekstarttime, $weekendtime])
                    ->orderBy('week_final_point', 'desc')
                    ->orderBy('single_final_point', 'desc')
                    ->groupBy('m.id')
                    ->limit(10)
                    ->get();
        $insertData = array();
        foreach($dataarr as $k=>$v){
            //用户的总点位
            foreach ($dataarr as $key=>$val){
                $total_point_data = DB::table('waihui_order')->select(DB::raw('SUM(final_point) as total_final_point'))->where(array('isstop'=>0,'ispersonal'=>0,'tel'=>$val->tel))->get()->toArray();
                $dataarr[$key]->total_final_point = $total_point_data?$total_point_data[0]->total_final_point:0;
            }
            
            //如果总赢点位小于0，那么奖金减半
            if($k == 0){ //第一名
                $insertData[$k]['bonus'] = 2000;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 2000 : 1000;
                
            }else if($k == 1){ //第二名
                $insertData[$k]['bonus'] = 1600;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 1600 : 800;
                
            }else if($k>=2 && $k<=5){ //第三名-第六名
                $insertData[$k]['bonus'] = 1000;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 1000 : 500;
                
            }else{  //第七名-第十名
                $insertData[$k]['bonus'] = 600;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 600 : 300;
                
            } 
           
            if($v->ordernum < 10){
                $insertData[$k]['desc'] = '策略数量不符';
                $insertData[$k]['status'] = 1;
                $insertData[$k]['actual_bonus'] = 0;
            }else if($v->week_final_point < 100){
                $insertData[$k]['desc'] = '周盈利点位不符';
                $insertData[$k]['status'] = 1;
                $insertData[$k]['actual_bonus'] = 0;
            }else{
                $insertData[$k]['desc'] = '';
                $insertData[$k]['status'] = 2;
            }
            
            $insertData[$k]['allpoint'] = round($v->total_final_point,2);
            $insertData[$k]['ranking'] = $k+1;
            $insertData[$k]['week_time'] = time();
            $insertData[$k]['week_profit'] = round($dataarr[$k]->week_final_point,2);
            $insertData[$k]['userid'] = $dataarr[$k]->id;
            $insertData[$k]['draw_status'] = 1;
            
            $id = DB::table('waihui_active_ranking')
                  ->insertGetId($insertData[$k]);  
            
        }

        if($id){
            return array('code'=>3,'msg'=>'入库成功,最后id为：'.$id);
        }else{
            return array('code'=>4,'msg'=>'入库失败');
        }
    }
    
    //查看跟单失败原因
    public function genDanFail(Request $request){
       $orderid = trim($request->get('orderid'));
       if($orderid == ''){
           return array('code'=>0,'msg'=>'单号不能为空');
       }
       $isExist = DB::table('waihui_order')->where("tradeid","$orderid")->first();
       if(!$isExist){
           return array('code'=>0,'msg'=>'单号不存在');
       }
       $data =  DB::table('waihui_gendan_fail as f')
                ->join('waihui_member as m','f.follower_tel','m.tel')
                ->select('f.follower_tel','f.reason','m.username','f.tradeid',
                        DB::raw('FROM_UNIXTIME(f.create_time,"%Y-%m-%d %H:%i:%s") as create_time')
                        )
                ->where('tradeid',"$orderid")
                ->get();
     
       if(count($data) == 0){
           return array('code'=>0,'msg'=>'没有漏单信息');
       }else{
           return array('code'=>1,'orderinfo'=>$data);
       }
    }
    
    
    //用户订阅详情
    public function follow(Request $request){
        $tel = trim($request->get('usertel'));
        $username = trim($request->get('username'));
        
        if(!preg_match('/^1[34578]\d{9}$/',$tel) && $username == ''){
            return array('code'=>0,'msg'=>'请输入正确的信息');
        }else if($tel != '' && $username == ''){
            $where['tel'] = $tel;
        }else if($tel == '' && $username != ''){ //当用户名不为空，手机号为空时
            $where['username'] = $username;
        }else{
            $where['tel'] = $tel;
            $where['username'] = $username;
        }  
        $isExist = DB::table('waihui_member')->where($where)->first();
        if(!$isExist){
            return array('code'=>0,'msg'=>'此用户不存在');
        }else{
            $followInfo = DB::table('waihui_follow')
                    ->select('analyst_name','status','direction',
                            DB::raw("FROM_UNIXTIME(follow_time,'%Y-%m-%d %H:%i:%s') as follow_time"),
                            DB::raw("FROM_UNIXTIME(update_time,'%Y-%m-%d %H:%i:%s') as update_time")
                            )
                    ->where("follower_id",$isExist->id)
                    ->orderBy('status','desc')
                    ->get();
            if(count($followInfo) == 0){
                return array('code'=>0,'msg'=>'此用户没有订阅过分析师');
            }else{
                return array('code'=>1,'followInfo'=>$followInfo);
            }
        }        
    }
    
    //查看订单详情
    public function orderInfo(Request $request){
        $orderid = trim($request->get('orderid'));
        if($orderid == ''){
            return array('code'=>0,'msg'=>'订单号不能为空');
        }
        $orderinfo = DB::table('waihui_order as o')
                    ->join('waihui_member as m','o.tel','m.tel')
                    ->select('typename','buy_status','m.username','begin_point','end_point','profit_point',
                            'loss_point','stop_status','final_point','isstop','target_profit_point','target_loss_point',
                            DB::raw("FROM_UNIXTIME(begin_time,'%Y-%m-%d %H:%i:%s') as begin_time"),
                            DB::raw("FROM_UNIXTIME(end_time,'%Y-%m-%d %H:%i:%s') as end_time")
                            )
                    ->where("tradeid","$orderid")->first();
        if(!$orderinfo){
            return array('code'=>0,'msg'=>'此订单不存在');
        }else{
            return array('code'=>1,'orderInfo'=>$orderinfo);
        }
    }
    
    
}
